<?php
namespace WMApi\Controller;

use WMApi\Model\WmCartModel;
use WMApi\Model\UsersModel;
use WMApi\Model\WmStoreModel;
use WMApi\Model\WmOrderInfoModel;
use WMApi\Model\WmOrderGoodsModel;
use SDXApi\Model\PaymentModel;
use SDXApi\Model\UseraddressModel;

use WMApi\Service\PublicServer;
use WMApi\Service\OrderService;
use WMApi\Service\BscService;
use Think\Model;

/**
 * Created by PhpStorm.
 * 店铺管理
 * User: caicm
 * Date: 2017/6/19
 * Time: 11:55
 */
class StoreController extends AppController {
    // 支付方式
    private $pay_id;
    
    
    /**
     * 订单收货确认
     * 
     * @param int uid 用户ID;
     * @param int order_id 订单ID;
     * 
     * @author ^2_3^
     */
    public function order_receive_affirm() {
        /// 需求:"配送中"的订单才可"收货确认",显示“订单已完成”;
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $order_id = I('post.order_id', 0, 'int');
        if( empty($uid) || empty($order_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 订单信息
        $where_oi = array(
            'uid' => $uid,
            'order_id' => $order_id
        );
        $arr_oi = M('wm_order_info')->where( $where_oi )->find();
        if( empty($arr_oi) ) {
            returnApiError('提示:参数错误;');
            
        }else if( $arr_oi['tail_end_status'] != 3 ) { //不是"配送中";
            returnApiError('提示:还未配送，不能确认收货;');
        }
        
        $time_opt = gmtime();
        M()->startTrans();
        
        /// 修改订单状态
        $data_oi = array(
            'tail_end_status' => TAIL_STATUS_RECEIVE, //已送达;
            'update_time' => $time_opt
        );
        $flag_oi = M('wm_order_info')->where( $where_oi )->save($data_oi);
        
        /// 添加操作记录
        $data_oa = array(
            'seller_id' => $arr_oi['seller_id'],
            'store_id'  => $arr_oi['store_id'],
            'order_id'  => $arr_oi['order_id'],
            'action_type'   => 1,   //操作类型 1-用户操作 2-后台操作;
            'remark'    => '用户确认收货;',
            'created'   => 'system',
            'add_time'  => $time_opt,
            'order_status'  => $arr_oi['order_status'],
            'seller_status' => $arr_oi['seller_status'],
            'trunk_line_status' => $arr_oi['trunk_line_status'],
            'tail_end_status' => TAIL_STATUS_RECEIVE,
            'op_type' => $arr_oi['op_type']
        );
        $flag_oa = M('wm_order_action')->data( $data_oa )->add();
        
        if( $flag_oi && $flag_oa ){
            M()->commit();
        }else {
            M()->rollback();
            returnApiError('提示: 确认收货异常, 请稍后重试;');
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 获取订单剩余时间
     * 
     * @param int $order_id 订单ID;
     * @param int $uid 用户ID;
     * 
     * @author ^2_3^
     */
    public function get_order_resttime() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $order_id = I('post.order_id', 0, 'int');
        $user_id = I('post.uid', 0, 'int');
        if( empty($order_id) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 订单信息
        $where_io = array(
            'order_id' => $order_id,
            'uid' => $user_id
        );
        $data = M('wm_order_info')
            ->field('order_id,order_sn,add_time,pay_fee')
            ->where($where_io)
            ->find();
        if( empty($data) ) {
            returnApiError('提示:订单不存在;');
        }
        
        $add_time = $data['add_time'];
        $pay_fee = $data['pay_fee'];
        
        /// 支付方式
        $userinfo = M('users')->where( array('user_id'=>$user_id) )->find();
        $user_amount = $userinfo['user_money'] + $userinfo['credit_line'];
        if( floatval($user_amount - $pay_fee) < 0 ) {
            $data['payment']='0'; //0其他支付;
        }else {
            $data['payment']='1'; //1余额支付;
        }
        
        /// 是否需要密码
        $data['need_pwd'] = '0';
        if( $user_amount >= $pay_fee || $user_amount > 50 && $user_amount < $pay_fee ) {
            $data['need_pwd'] = '1';
        }
        
        /// 支付剩余时间
        $rest_pay_time = REST_PAY_TIME-(gmtime()-$add_time);
        $data ['rest_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;
        
        $data['add_time'] = localtotime($data['add_time']);
        $data['add_date'] = local_date('Y-m-d H:i:s', $data['add_time']);
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 订单列表
     *
     * @param int $uid 用户ID;
     * @param int $page 分页，默认为1;
     * 
     * @author ^2_3^
     */
    public function order_list() {
        $start = microtime(true);
    
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        if( empty($uid) ) {
            returnApiError('提示:缺少用户参数;');
        }
        $page = I('post.page', 0, 'int');
        empty($page) && $page = 1;
        
        /// 订单数据
        $order_model = new WmOrderInfoModel();
        //-/ 订单总量
        $order_count = $order_model->get_order_count( $uid );
        //-/ 分页数据
        $data = show_page($order_count, $page);
        //-/ 订单列表
        $order_list = $order_model->get_order_list( $uid, "{$data['firstpage']}, {$data['pagesize']}" );
        $p_server = new PublicServer();
        foreach ( $order_list as $key=>$arr ){
            // 下单时间
            $order_list[$key]['add_date'] = local_date('Y-m-d H:i:s', $arr['add_time']);
            $order_list[$key]['add_time'] = localtotime( $arr['add_time'] );
            //-/ 订单状态
            $status_text = $p_server->get_order_status_text($arr['order_status'], $arr['seller_status'], $arr['tail_end_status']);
            $order_list[$key]['status_text'] = $status_text;
            //-/ 支付剩余时间
            $rest_pay_time = REST_PAY_TIME-(gmtime()-$arr['add_time']);
            $order_list[$key]['rest_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;
        }
        $data['order_list'] = $order_list;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 订单取消
     * 
     * @param int uid 用户ID;
     * @param int order_id 订单编号;
     * 
     * @author ^2_3^
     */
    public function order_cancel() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $order_id = I('post.order_id', 0, 'int');
        if( empty($uid) || empty($order_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 订单信息
        $where_oi = array(
            'oi.order_id' => $order_id
        );
        $info_oi = M('wm_order_info oi')->where( $where_oi )->find();
        if( empty($info_oi) ) {
            returnApiError('提示:没有相应订单;');
            
        }else if( $info_oi['uid'] != $uid ) {
            returnApiError('提示:不是此用户订单;');
            
        }else if( $info_oi['order_status'] == 2 ) {
            returnApiError('提示:订单已取消;');
            
        }else if( $info_oi['order_status'] == 3 ) {
            returnApiError('提示:订单已退款，无法取消;');
            
        }else if( $info_oi['seller_status'] == 1 ) {
            returnApiError('提示:商家已接单，不能手动取消订单，请联系商家;');
            
        }else if( in_array($info_oi['seller_status'], array(2, 3)) ) { //商家状态:2-拒接单 3-取消订单;
            returnApiError('提示:商家已经处理, 不能再手动取消;');
            
        }else if( $info_oi['tail_end_status'] == 4 ) {
            returnApiError('提示:订单已送达，不能取消，请联系商家;');
        }
        
        /// 未付款->取消
        if( $info_oi['order_status'] == 0 ) {
            $time_opn = gmtime();
            
            $model = new Model();
            $model->startTrans();
            
            //-/ 订单取消
            $data_oi = array(
                'order_status' => 2, //订单状态 （0-未付款 1-已付款 2-已取消 3-已退款）;
                'cancel_type' => 2, //订单取消类型（1-自动取消 2-手动取消）;
                'cancel_time' => $time_opn,
                'update_time' => $time_opn
            );
            $where_oi = array(
                'order_id' => $order_id,
                'uid' => $uid
            );
            $flag_oi = M('wm_order_info')->where($where_oi)->save($data_oi);
            
            //-/ 操作记录
            $data_oa = array(
                'seller_id' => $info_oi['seller_id'],
                'store_id' => $info_oi['store_id'],
                'order_id' => $info_oi['order_id'],
                'action_type' => 1, //操作类型 1-用户操作 2-后台操作;
                'remark' => '用户取消订单',
                'created' => '用户',
                'add_time' => $time_opn,
                'order_status' => 2,
                'seller_status' => $info_oi['seller_status'],
                'trunk_line_status' => $info_oi['trunk_line_status'],
                'tail_end_status' => $info_oi['tail_end_status'],
                'op_type' => $info_oi['op_type']
            );
            $flag_oa = M('wm_order_action')->add($data_oa);
            
            if( $flag_oi && $flag_oa ) {
                $model->commit();
                returnApiSuccess(array(), '提示:取消成功;');
                
            }else {
                $model->rollback();
                $arr_err = array(
                    'flag_oi' => $flag_oi,
                    'flag_oa' => $flag_oa
                );
                returnApiError('提示:取消失败, 请稍后重试, 或联系客服;', $arr_err);
            }

        /// 已付款_未接单->取消退款
        }else {
            //returnApiSuccess('提示:已付款取消正在升级中, 敬请期待;');
            
            /// 支付方式(pay_id) 1-微信支付 2-支付宝 3-余额支付 7-京东支付;
            $flag_refund = false;
            $pay_id = $info_oi['pay_id'];
            switch ($pay_id){
                //-/ 取消_退款_余额支付
                case 3:
                    $flag_refund = self::refund_balance( $info_oi );
                    break;
                //-/ 取消_退款_微信支付/支付宝支付
                case 1:
                case 2:
                    $arr_oi = array(
                        "order_id" => $info_oi['order_id'],
                        "order_sn" => $info_oi['order_sn'],
                        "uid" => $info_oi['uid'],
                        "pay_id" => $pay_id
                    );
w_log('wm_refund', '外卖退款开始; --- --START-- ---');
w_log('wm_refund', '退款请求参数 '.json_encode($arr_oi));
                    $data_refund = postToEchouchApi('WmAip','order_refund', $arr_oi);
w_log('wm_refund', '外卖请求结果 '.json_encode($data_refund));
w_log('wm_refund', '外卖退款结束; --- --END-- ---');
                    
                    $flag_refund = $data_refund['status'];
                    $data['msg'] = $data_refund['msg'];
                    $data['err'] = $data_refund['err'];
                    
                    break;
                default:
                    returnApiError('提示:取消退款异常,请联系客服人员;');
            }
            
            if( !$flag_refund ) {
                returnApiError('提示:订单取消退款失败,请稍后重试;', $data);
            }
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * API调用ECTouch示例
     * http://apidev.cyb.cn/wmindex.php?s=/store/post_to_ecth
     * @author ^2_3^
     */
    public function post_to_ecth(){
        $arr_oi = array(
            "order_id" => 75,
            "uid" => 25863
        );
        $data = postToEchouchApi('WmAip','order_refund', $arr_oi);
    
        print_r($data);
    }
    
    /**
     * 取消_退款_余额支付
     * 
     * @param array $arr_order 订单信息;
     * 
     * @author ^2_3^
     */
    private function refund_balance( $arr_order = array() ) {
        $flag = true;
        if( !is_array($arr_order) && empty($arr_order) ) {
            returnApiError('提示:取消_退款_余额支付 失败,请稍后重试;');
        }
        
        if( $arr_order['order_status'] != 1 ) {
            returnApiError('提示:订单已处理，不能再退款;');
        }
        
        /// 支付信息
        $where_pl = array(
            'pl.order_id' => $arr_order['order_id'],
            'pl.order_type' => 2,
            'pl.is_paid' => 1
        );
        $arr_plog = M('pay_log pl')
            ->where( $where_pl )
            ->find();
// w_log('cyb_log', M()->getLastSql());
        //-/ 验证
        if( empty($arr_plog) ||  $arr_plog['order_amount'] != $arr_order['pay_fee'] ) {
            returnApiError('提示:订单退款异常,请联系客服;');
        }

        $flag_oi = false; //订单信息标识;
        $flag_oa = false; //订单操作标识;
        $flag_u = false; //用户账号标识;
        $flag_al = false; //账户记录标识;
        $pay_fee = $arr_order['pay_fee']; //订单余额;
        $time_opt = gmtime();
        
        M()->startTrans();
        
        //1/ 修改订单为已退款状态
        $where_oi = array(
            'order_id' => $arr_order['order_id'],
            'uid'   => $arr_order['uid']
        );
        $data_oi = array(
            'order_status' => ORDER_STATUS_REFUNDED,
            'update_time' => $time_opt
        );
        $flag_oi = M('wm_order_info')->where( $where_oi )->save( $data_oi );
        
        //2/ 插入订单操作记录(wm_order_action)
        $data_oa = array(
            'seller_id' => $arr_order['seller_id'],
            'store_id'  => $arr_order['store_id'],
            'order_id'  => $arr_order['order_id'],
            'action_type'   => 1,   //操作类型 1-用户操作 2-后台操作;
            'remark'    => '用户退款',
            'created'   => 'system',
            'add_time'  => $time_opt,
            'order_status'  => ORDER_STATUS_REFUNDED, //已退款;
            'seller_status' => $arr_order['seller_status'],
            'trunk_line_status' => $arr_order['trunk_line_status'],
            'tail_end_status' => $arr_order['tail_end_status'],
            'op_type' => $arr_order['op_type']
        );
        $flag_oa = M('wm_order_action')->data( $data_oa )->add();
        
        //3/ 更新用户账号金额(users)[添加]
        $where_u = array(
            "user_id" => $arr_order['uid']
        );
        $flag_u = M('users')->where($where_u)->setInc('user_money', $arr_plog['order_amount']);
        
        //4/ 插入账户变动记录(account_log)
        $data_al = array(
            "user_id" => $arr_order['uid'],
            "user_money" => $arr_plog['order_amount'],
            "change_time" => $time_opt,
            "change_desc" => sprintf('外卖订单 %s退款;', $arr_order['order_sn']),
            "change_type" => 99,
            "p_log_id" => $arr_plog['log_id'],
            "action_user" => 'user'
        );
        $flag_al = M('account_log')->add( $data_al );
        
        if( $flag_oi && $flag_oa && $flag_u && $flag_al ) {
            M()->commit();
            $flag = true;
        }else {
            M()->rollback();
        }
        
        return $flag;
    }
    
    /**
     * 订单详情
     * 
     * @param int order_id 订单ID;
     * @param string order_sn 订单号;
     * 
     * @author ^2_3^
     */
    public function order_info() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $order_id = I('post.order_id', 0, 'int');
        $order_sn = I('post.order_sn', '', 'trim');
        if( empty($order_id) && empty($order_sn) ) {
            returnApiError("提示:缺少参数;");
        }
        
        $order_model = new WmOrderInfoModel();
        $order_list = $order_model->get_order_details_info($order_id, $order_sn);
        if( empty($order_list) ) {
            returnApiError('提示:没有相应订单信息;');
        }
        
        $order_info = array();
        $order_goods = array();
        $p_server = new PublicServer();
        foreach ( $order_list as $okey=>$oarr ){
            $order_info['order_id'] = $oarr['order_id'];
            $order_info['order_sn'] = $oarr['order_sn'];
            $order_info['seller_id'] = $oarr['seller_id'];
            $order_info['store_id'] = $oarr['store_id'];
            $order_info['uid'] = $oarr['uid'];
            $order_info['order_status'] = $order_status = $oarr['order_status'];
            $order_info['seller_status'] = $seller_status = $oarr['seller_status'];
            $order_info['tail_end_status'] = $tail_end_status = $oarr['tail_end_status'];
            $order_info['status_text'] = $p_server->get_order_status_text($order_status, $seller_status, $tail_end_status);
            $order_info['add_date'] = local_date('Y-m-d H:i:s', $oarr['add_time']);
            $order_info['goods_num'] += $oarr['goods_number'];
            $order_info['add_time'] = localtotime($oarr['add_time']);
            $order_info['pay_date'] = local_date('Y-m-d H:i:s', $oarr['pay_time']);
            $order_info['pay_time'] = localtotime($oarr['pay_time']);
            //-/　商品合计
            $order_info['goods_amount'] = $oarr['goods_amount'];
            $order_info['consignee'] = $oarr['consignee'];
            $order_info['mobile'] = $oarr['mobile'];
            $order_info['address'] = $oarr['address'];
            $order_info['address_name'] = $oarr['address_name'];
            $order_info['courier_name'] = $oarr['courier_name'];
            $order_info['courier_phone'] = $oarr['courier_phone'];
            //-/ 期望时间
            $se_date_start = local_date('Y-m-d H:i:s', $oarr['shipping_expect_time_start']);
            $order_info['shipping_expect_start'] = $se_date_start;
            $se_time_start = local_date('H:i:s', $oarr['shipping_expect_time_start']);
            $order_info['shipping_e_time_start'] = $se_time_start;
            $se_date_end = local_date('Y-m-d H:i:s', $oarr['shipping_expect_time_end']);
            $order_info['shipping_expect_end'] = $se_date_end;
            $se_time_end = local_date('H:i:s', $oarr['shipping_expect_time_end']);
            $order_info['shipping_e_time_end'] = $se_time_end;
            $order_info['shipping_expect'] = "{$se_date_start} 到 {$se_date_end}";
            $order_info['shipping_expect_time'] = "{$se_time_start} 到 {$se_time_end}";
            $order_info['postscript'] = $oarr['postscript'];
            $order_info['pay_id'] = $oarr['pay_id'];
            $order_info['pay_type'] = $p_server->get_pay_type($oarr['pay_id']);
            $order_info['shipping_fee'] = $oarr['shipping_fee'];
            //-/ 实付金额
            $order_info['pay_fee'] = $oarr['pay_fee'];
            
            $goods_tmp['goods_id'] = $oarr['goods_id'];
            $goods_tmp['goods_name'] = $oarr['goods_name'];
            $goods_tmp['sku_id'] = $oarr['sku_id'];
            $goods_tmp['goods_price'] = $oarr['goods_price'];
            $goods_tmp['market_price'] = $oarr['market_price'];
            $goods_tmp['goods_number'] = $oarr['goods_number'];
            $goods_tmp['main_attr_name'] = $oarr['main_attr_name'];
            $goods_tmp['main_attr_value_name'] = $oarr['main_attr_value_name'];
            $goods_tmp['sec_attr_name'] = $oarr['sec_attr_name'];
            $goods_tmp['sec_attr_value_name'] = $oarr['sec_attr_value_name'];
            $goods_tmp['goods_img'] = $oarr['goods_img'];
            $order_goods[] = $goods_tmp;
        }
        
        /// 店铺信息
        $wmstoremodel = new WmStoreModel();
        $store_arr = $wmstoremodel->find_store_info($order_info['seller_id'], $order_info['store_id']);
        $store_info['store_id'] = $store_arr['store_id'];
        $store_info['seller_id'] = $store_arr['seller_id'];
        $store_info['store_name'] = $store_arr['store_name'];
        $store_info['store_introduce'] = $store_arr['store_introduce'];
        $store_info['store_img'] = $store_arr['store_img'];
        $store_info['shipping_fee'] = $store_arr['shipping_fee'];
        $store_info['starting_money'] = $store_arr['starting_money'];
        $store_info['contacts_phone'] = $store_arr['contacts_phone'];
        $data['store_info'] = $store_info;
        
        /// 订单支付剩余时间
        $rest_pay_time = REST_PAY_TIME - ( time() - $order_info['add_time'] );
        $order_info ['rest_pay_time'] = $rest_pay_time < 0 ? 0 : $rest_pay_time;

        $data['order_info'] = $order_info;
        $data['order_goods'] = $order_goods;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 订单支付 ^2_3^ TODO
     * 
     * @param int uid 用户ID;
     * @param string openid 微信用户唯一识别;
     * @param int order_id 订单ID;
     * @param int pay_id 支付方式id(3-余额支付[balance]; 1-微信支付[wxpay]; 2-支付宝[alipay]; 7-京东支付[jdpay]);
     * @param string pay_pwd 支付密码(密文传输, md5(password+"sdxPay"));
     * @param int pay_type 2-支付订单; 1-充值; (微信支付时要求，其他的不是必需);
     * @param string app_type 默认为空, 为公众号支付; “app”:app支付; “native”：原生扫码支付;
     * @param string order_amount 订单应付金额;
     * @param int IS_HD 是否HD, 默认为-1, 1为Android, 2为IOS;
     * 
     * @author ^2_3^
     */
    public function order_pay() {
        /// 请求方式
        if( !IS_POST ) {
            returnApiError('unknown request mode;');
        }
        $res_arr = array();
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $openid = I('post.openid', '', 'trim');
        $order_id = I('post.order_id', 0, 'int');
        $pay_id = I('post.pay_id', 0, 'int');
        $pay_pwd = I('post.pay_pwd', '', 'trim');
        $pay_type = I('post.pay_type', 0, 'int');
        $app_type = I('post.app_type', '', 'trim');
        $order_amount = I('post.order_amount', '', 'trim') + 0;
        $is_hd = I('post.IS_HD', '-1', 'int');
        
        $this->pay_id = $pay_id;
        
        if( empty($app_type) ) {
            $app_type = 'jspay'; //公众号支付;
        }
        
        /// 参数验证
        //-/ 订单ID
        if( empty($order_id) ) {
            $res_arr['error_code'] = '105';
            returnApiError('order_id参数不存在;', $res_arr);
        }
        //-/ 支付方式
        if( empty($pay_id) ) {
            $res_arr['error_code'] = '106';
            returnApiError('pay_id参数不存在;', $res_arr);
        }
        //-/ 订单是否存在
        $where_oi = array(
            "order_id" => $order_id
        );
        $order_info = M('wm_order_info')->where($where_oi)->find();
        if( empty($order_id) ) {
            $res_arr['error_code'] = '104';
            returnApiError('订单不存在;', $res_arr);
        }
        //-/ 订单为已支付
        if( $order_info['order_status'] == ORDER_STATUS_PAYED ) {
            $res_arr['error_code'] = '101';
            returnApiError('订单已支付;', $res_arr);
        }
        //-/ 订单为已取消
        if( $order_info['order_status'] == ORDER_STATUS_CANCELED ) {
            $res_arr['error_code'] = '109';
            returnApiError('订单已取消;', $res_arr);
        }
        
        /// 支付方式
        $pay_code = D('SDXApi/Payment')->get_pay_code($pay_id);
        if( empty($pay_code) ) {
            returnApiError('pay_id参数无效;');
        }
        switch ( $pay_code ){
            //-/ 余额支付
            case 'balance':
                // 密码加密
                //$pay_pwd = md5($pay_pwd."sdxPay");
                $this->balance_pay( $order_info, $pay_pwd );
                break;
            //-/ 支付宝支付
            case 'alipay':
                /// TODO
//                 returnApiSuccess('正在优化中，敬请期待!');

                $this->alipay( $order_info, $app_type ); //$app_type默认为空, 为公众号支付; “app”:app支付; “native”：原生扫码支付;
                break;
            //-/ 微信支付
            case 'wxpay':
                $this->wxpay( $order_info );
                break;
            //-/ 京东支付
            case 'jdpay':
                returnApiSuccess('正在优化中，敬请期待!');
                $this->jdpay($order_info, $app_type);
                break;
        }
        
    }
    
    /**
     * 余额支付 [ECTouch_StoreService->balance_pay()]
     * @param array $order_info 订单信息;
     * @param string $pwd 余额支付密码;
     * @param bool $needpwd 是否需要密码(混合支付会调用);
     * 
     * @author ^2_3^
     */
    public function balance_pay( $order_info = array(), $pwd = '', $needpwd = true ) {
        $res_arr = array();
        
        /// 密码验证(必须时)
        //-/ 非空验证
        if( empty($pwd) && $needpwd === true ) {
            returnApiErrorExample('请输入余额支付密码;');
        }
        //-/ 有效验证
        $order_service = new OrderService();
        if( $needpwd === true ) {
            $pwd_flag = $order_service->check_pay_password($order_info['uid'], $pwd);
            if( !$pwd_flag ) {
                returnApiError( '余额支付密码错误;' );
            }
        }
        
        /// 用户信息
        $where_u = array(
            "user_id" => $order_info['uid']
        );
        $user_info = M('users')->where($where_u)->find();
        //-/ 检查余额
        if( $order_info['pay_fee'] > ( $user_info['user_money'] + $user_info['credit_line'] ) ) {
            $res_arr['error_code'] = '103';
            $res_arr['order_id'] = $order_info['order_id'];
            $res_arr['order_sn'] = $order_info['order_sn'];
            $res_arr['pay_fee'] = $order_info['pay_fee'];
            returnApiError('账号余额不足;', $res_arr);
        };
        
        /// 1、插入支付日志(pay_log)[未支付]
        $pay_log_id = D('SDXApi/Payment')->get_paylog_id($order_info['order_id'], PAY_WM_ORDER);
        if( empty($pay_log_id) ) {
            $pay_log_id = D('SDXApi/Payment')->insert_pay_log($order_info['order_id'], $order_info['pay_fee'], PAY_WM_ORDER);
        }
        
        /// 2、修改订单支付类型(wm_order_info)
        $order_service->change_order_pay_type($order_info, 3);
        
        /// 3、修改订单支付状态(wm_order_info)
        $result_pay = $order_service->order_paid( $order_info['order_sn'] );
        
        if( $result_pay['status'] ) {
            if( $needpwd === true ) {
                $oi_info = M('wm_order_info')->field('
                        order_id,
                        order_sn,
                        pay_fee
                    ')
                    ->where( array('order_id'=>$order_info['order_id']) )
                    ->find();
                $oi_info = array_merge($result_pay, $oi_info);
                returnApiSuccess($oi_info, '余额支付成功;');
            }
            
            return true;
        }else {
            if( $needpwd === true ) {
                $oi_info = M('wm_order_info')->field('
                        order_id,
                        order_sn,
                        pay_fee
                    ')
                    ->where( array('order_id'=>$order_info['order_id']) )
                    ->find();
                returnApiError('余额支付失败，请重试或者联系客服;', $oi_info);
            }
            
            return false;
        }
        
    }
    
    /**
     * 支付宝支付 TODO
     * @param array $order_info 订单信息;
     * @param string $trade_type 默认为空, 为公众号支付; “app”:app支付; “native”: 原生扫码支付;
     */
    private function alipay( $order_info = array(), $trade_type = '' ) {
        $res_arr = array();
        
        /// 金额验证
        if ($order_info['pay_fee'] <= 0) {
            $res_arr['error_code'] = "102";
            returnApiError('支付金额必须大于0', $res_arr);
        }
        
        /// 支付金额
        $order_service = new OrderService();
        $pay_amount = $order_service->check_money($order_info['pay_fee'], $order_info['uid']);
        
        /// 参数处理
        $is_hd = I('post.IS_HD', -1, 'int');
        $is_h5 = I('post.is_h5', 0, 'int');
        $version = I('post.version', 0, 'trim');
        $pwd = I('post.pay_pwd', '', 'trim');
        
        /// 版本处理
        $iosversion = explode('.', $version);
        $iosversion = str_pad($iosversion[0], 3, "0", STR_PAD_LEFT).
            str_pad($iosversion[1], 3, "0", STR_PAD_LEFT).
            str_pad($iosversion[2], 3, "0", STR_PAD_LEFT);
        
        /// 用户金额
        $where_u = array(
            'user_id' => $order_info['uid']
        );
        $user_money = M('users')->where( $where_u )->getField('user_money');
        
        /// 是否需要支付密码
        if ( $user_money > 50 && 
            ($is_hd == '2' && $iosversion > 002003053 || 
             $is_hd == '1' && $version > 49 || 
             $is_h5 == '1' && $version > 0) 
            && $pay_amount != $order_info['pay_fee']) 
        {
            
            if (empty($pwd)) {
                returnApiError('请输入密码;');
            }
            
            if ( !$order_service->check_pay_password($order_info['uid'], $pwd) ) {
                returnApiError('支付密码错误;');
            }
        }
        
        $pay_amount = sprintf( '%.2f', $pay_amount );
        
        /// 1、插入支付日志(pay_log)[未支付];
        $payment_m = new PaymentModel();
        $pay_log_id = $payment_m->get_paylog_id($order_info['order_id'], PAY_WM_ORDER);
        if( empty($pay_log_id) ) {
            $pay_log_id = $payment_m->insert_pay_log($order_info['order_id'], $order_info['pay_fee'], PAY_WM_ORDER);
        }
        $order_info['log_id'] = $pay_log_id;
        
        /// 2、修改订单支付类型(wm_order_info);
        $order_service->change_order_pay_type( $order_info, $this->pay_id );
        
        /// 支付参数
        $out_trade_no = $order_info['order_sn'];
        $subject = "订单支付，金额:" . $order_info['pay_fee']; //订单名称,必填;
        $total_fee = $pay_amount;
        $return_host = $order_service->get_return_host( $_SERVER['HTTP_HOST'] );
        $show_url = "http://".$return_host."/index.php"; //收银台页面上，商品展示的超链接，必填;
        $body = '食得鲜-订单支付';
        $notify_url = "http://" . $_SERVER['HTTP_HOST'] . "/wm_alipay_notice.php"; //异步判断支付结果;
        $return_url = "http://".$return_host."/index.php";
        
        if ($trade_type == "app") {
            $alipay_from['payinfo'] = $payment_m->app_alipay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $show_url, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of Alipay');
            
        } elseif($trade_type == "native"){
            $notify_url = "http://" . $_SERVER['HTTP_HOST'] . "/wm_alipay_scan_pay_notice.php";//异步判断支付结果;
            $alipay_from['payinfo'] = $payment_m->scan_alipay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $show_url, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of Alipay');
            
        }else {
            $alipay_from['from'] = $payment_m->alipay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $show_url, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of Alipay,Please show this from to page');
        }
        
    }
    
    /**
     * 微信支付
     * @param array $order_info 订单信息;
     * 
     * @author ^2_3^
     */
    private function wxpay( $order_info = array() ) {
        $res_arr = array();
        
        returnApiError('温馨提示：微信支付请调用另外支付接口;');
        
        return $res_arr;
    }
    
    /**
     * 京东支付
     * @param array $order_info 订单信息;
     * @param string $trade_type 默认为空, 为公众号支付; “app”:app支付; “native”：原生扫码支付;
     */
    private function jdpay( $order_info = array(),  $trade_type = '') {
        $res_arr = array();
        
        /// 订单金额 验证
        if( $order_info['pay_fee'] <= 0 ) {
            $res_arr['error_code'] = '102';
            returnApiError('支付金额必须大于0', $res_arr);
        }
        
        /// 支付金额
        $order_service = new OrderService();
        $pay_amount = $order_service->check_money($order_info['pay_fee'], $order_info['user_id']);
        
        /// 参数处理
        $is_hd = I('post.IS_HD', -1, 'int');
        $is_h5 = I('post.is_h5', 0, 'int');
        $version = I('post.version', 0, 'trim');
        $pwd = I('post.pay_pwd', '', 'trim');
        
        /// 版本处理
        $iosversion = explode('.', $version);
        $iosversion = str_pad($iosversion[0], 3, "0", STR_PAD_LEFT).
        str_pad($iosversion[1], 3, "0", STR_PAD_LEFT).
        str_pad($iosversion[2], 3, "0", STR_PAD_LEFT);
        
        /// 用户金额
        $where_u = array(
            'user_id' => $order_info['uid']
        );
        $user_money = M('users')->where( $where_u )->getField('user_money');
        
        /// 是否需要支付密码
        if ( $user_money > 50 &&
            ($is_hd == '2' && $iosversion > 002003053 ||
                $is_hd == '1' && $version > 49 ||
                $is_h5 == '1' && $version > 0)
            && $pay_amount != $order_info['pay_fee'])
        {
        
            if (empty($pwd)) {
                returnApiError('请输入密码;');
            }
        
            if ( !$order_service->check_pay_password($order_info['uid'], $pwd) ) {
                returnApiError('支付密码错误;');
            }
        }
        
        $pay_amount = sprintf( '%.2f', $pay_amount );
        
        /// 插入支付日志(pay_log)[未支付]
        $payment_m = new PaymentModel();
        $pay_log_id = $payment_m->get_paylog_id($order_info['order_id'], PAY_WM_ORDER);
        if( empty($pay_log_id) ) {
            $pay_log_id = $payment_m->insert_pay_log($order_info['order_id'], $order_info['pay_fee'], PAY_WM_ORDER);
        }
        $order_info['log_id'] = $pay_log_id;
        
        /// 修改订单支付类型(wm_order_info)
        $order_service->change_order_pay_type( $order_info, $this->pay_id );
        
        /// 支付参数
        $out_trade_no = $order_info['order_sn'];
        $total_fee = $pay_amount;
        $subject = "订单支付，金额:" . $total_fee; //订单名称，必填;
        $body = '食得鲜-订单支付';
        $return_host = $order_service->get_return_host($_SERVER['HTTP_HOST']);
//         $notify_url = "http://" . $_SERVER['HTTP_HOST'] . "/jd_pay_notice.php";              //异步判断支付结果;
        $notify_url = "http://" . $_SERVER['HTTP_HOST'] . "/wm_jd_pay_notice.php";              //异步判断支付结果;
//         $return_url = "https://".$return_host."/?index=/payOrd?ord=".$order['order_id'];     //同步判断地址;
        $return_url = "https://".$return_host."/?index=/payOrd?ord=".$order_info['order_id'];     //同步判断地址;
        
        if ($trade_type == "app") {
            $alipay_from['payinfo'] = $payment_m->app_jdpay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER,
                    $order_info['uid']
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of JD');
            
        }elseif($trade_type == "native"){
            $alipay_from['payinfo'] = $payment_m->scan_jdpay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER,
                    $order_info['uid']
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of JD');
            
        }else {
            $alipay_from['from'] = $payment_m->jdpay(
                    $out_trade_no, 
                    $subject, 
                    $total_fee, 
                    $body, 
                    $notify_url, 
                    $return_url, 
                    PAY_WM_ORDER,
                    $order_info['uid']
                );
            returnApiSuccess($alipay_from, 'Transfer from the success of JD,Please show this from to page');
        }
        
    }
    
    /**
     * 订单提交
     * 
     * @param int uid 用户ID;
     * @param int address_id 用户地址ID;
     * @param int seller_id 商家ID;
     * @param int store_id 店铺ID;
     * @param string postscript 订单留言;
     * @param string expect_time 期望配送时间;
     * 
     * @author ^2_3^
     */
    public function order_submit() {
        $start = microtime(true);
        
        /// 参数获取
        $uid = I('post.uid', 0, 'int');
        $address_id = I('post.address_id', 0, 'int');
        $seller_id = I('post.seller_id', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        $postscript = I('post.postscript', '', 'trim');
        $expect_time = I('post.expect_time', '', 'trim');
        if( empty($uid) || empty($address_id) || empty($seller_id) || empty($store_id) || empty($expect_time) ) {
            returnApiError('提示:参数缺失;');
        }
        
        //// 订单数据
        $order_data = array();
        
        /// 店铺信息
        $store_model = new WmStoreModel();
        $store_info = $store_model->find_store_info($seller_id, $store_id);
        //-/ 休息状态/营业时间 处理
        $time_str = date('Hi');
        if( $store_info['store_sw'] != 1 || $time_str < $store_info['start_time'] 
            || $time_str > $store_info['end_time'] 
        ) {
            returnApiError('提示:店铺还没营业,欢迎稍后下单;');
        }
        
        $order_data['seller_id'] = $store_info['seller_id'];
        $order_data['store_id'] = $store_info['store_id'];
        $order_data['store_name'] = $store_info['store_name'];
        $order_data['shipping_fee'] = $store_info['shipping_fee'];
        
        /// 商品列表(购物车)
        $cart_model = new WmCartModel();
        $goods_list = $cart_model->get_goods_list($uid, $store_id);
        
        /// 商品处理
        //-/ 商品总金额
        $goods_amount = 0;
        //-/ 商品数量
        $goods_number = 0;
        foreach ($goods_list as $g_key=>$g_arr){
            /// 商品验证
            if( $g_arr['state'] != 1 || $g_arr['g_is_del'] || ( $g_arr['is_sku'] && $g_arr['gs_is_del'] ) ) {
                returnApiError('提示:有商品已下架, 请先在购物车删除再提交;');
            }

            // 商品价格
            $goods_price = empty($g_arr['sku_id']) ? $g_arr['g_now_goods_price'] : $g_arr['gs_now_goods_price'];
            // 商品总金额
            $goods_amount += $goods_price * $g_arr['goods_num'];
            // 商品数量
            $goods_number += $g_arr['goods_num'];
            
        }
        
        /// 用户信息
        $user_model = new UsersModel();
        $user_info = $user_model->get_user_address_info($uid, $address_id);
        $order_data['uid'] = $user_info['uid'];
        $order_data['user_name'] = $user_info['user_name'];
        $order_data['tail_end_status'] = 1;
        $order_data['province'] = $user_info['province'];
        $order_data['province_name'] = $user_info['province_name'];
        $order_data['city'] = $user_info['city'];
        $order_data['city_name'] = $user_info['city_name'];
        $order_data['district'] = $user_info['district'];
        $order_data['district_name'] = $user_info['district_name'];
        $order_data['address'] = $user_info['address'];
        $order_data['address_name'] = $user_info['address_name'];
        $order_data['sign_building'] = $user_info['sign_building'];
        $order_data['consignee'] = $user_info['consignee'];
        $order_data['mobile'] = $user_info['mobile'];
        $order_data['longitude'] = $user_info['longitude'];
        $order_data['latitude'] = $user_info['latitude'];
        
        /// 其他数据
        $order_data['postscript'] = $postscript;
        $order_data['goods_amount'] = $goods_amount;
        //-/ 实付金额
        $order_data['pay_fee'] = $goods_amount + $store_info['shipping_fee'];
        $order_data['goods_number'] = $goods_number;
        $order_data['order_sn'] = get_order_sn();
        $order_data['add_time'] = gmtime();
        //-/ 期望时间
        $publicserver = new PublicServer();
        $expect_arr = $publicserver->get_expect_time($expect_time);
        $order_data['shipping_expect_time_start'] = $expect_arr['shipping_expect_time_start'];
        $order_data['shipping_expect_time_end'] = $expect_arr['shipping_expect_time_end'];
        
        $oi_model = new WmOrderInfoModel();
        $oi_model->startTrans();
        $order_id = $oi_model->user_add_order($order_data);
        
        //// 订单商品数据
        $og_data = array();
        $g_time = gmtime();
        foreach ($goods_list as $gkey=>$garr){
            $temp_arr = array();
            
            $temp_arr['order_id'] = $order_id;
            $temp_arr['uid'] = $garr['uid'];
            $temp_arr['seller_id'] = $store_info['seller_id'];
            $temp_arr['store_id'] = $garr['store_id'];
            $temp_arr['store_name'] = $store_info['store_name'];
            $temp_arr['goods_id'] = $garr['goods_id'];
            $temp_arr['goods_name'] = $garr['goods_name'];
            $temp_arr['goods_sn'] = $garr['goods_sn'];
            $temp_arr['goods_number'] = $garr['goods_num'];
            $temp_arr['market_price'] = $garr['g_now_market_price'];
            $og_goods_price = empty($garr['sku_id']) ? $garr['g_now_goods_price'] : $garr['gs_now_goods_price'];
            $temp_arr['goods_price'] = $og_goods_price;
            $temp_arr['total_price'] = $garr['goods_num'] * $og_goods_price;
            $temp_arr['sku_id'] = $garr['sku_id'];
            $temp_arr['main_attr_name'] = empty($garr['main_attr_name']) ? '' : $garr['main_attr_name'];
            $temp_arr['main_attr_value_name'] = empty($garr['main_attr_value_name']) ? '' : $garr['main_attr_value_name'];
            $temp_arr['sec_attr_name'] = empty($garr['sec_attr_name']) ? '' : $garr['sec_attr_name'];
            $temp_arr['sec_attr_value_name'] = empty($garr['sec_attr_value_name']) ? '' : $garr['sec_attr_value_name'];
            $temp_arr['add_time'] = $g_time;
            $og_data[] = $temp_arr;
        }
        
        $og_model = new WmOrderGoodsModel();
        $og_flag = $og_model->user_add_ogoods($og_data);
        
        if( $order_id && $og_flag ) {
            $oi_model->commit();
            
            /// 清空购物车
            $wmcartmodel = new WmCartModel();
            $wmcartmodel->cart_clean_up($uid, $store_id);
        }else {
            $oi_model->rollback();
            returnApiError('提示:订单失败,请稍后重试;');
        }
        
        /// 订单数据
        $order_model = new WmOrderInfoModel();
        $order_list = $order_model->get_order_details_info($order_id);
        if( empty($order_list) ) {
            returnApiError('提示:没有相应订单信息;');
        }
        
        $order_info = array();
        $order_goods = array();
        $p_server = new PublicServer();
        foreach ( $order_list as $okey=>$oarr ){
            $order_info['order_id'] = $oarr['order_id'];
            $order_info['order_sn'] = $oarr['order_sn'];
            $order_info['seller_id'] = $oarr['seller_id'];
            $order_info['store_id'] = $oarr['store_id'];
            $order_info['order_status'] = $order_status = $oarr['order_status'];
            $order_info['seller_status'] = $seller_status = $oarr['seller_status'];
            $order_info['tail_end_status'] = $tail_end_status = $oarr['tail_end_status'];
            $order_info['status_text'] = $p_server->get_order_status_text($order_status, $seller_status, $tail_end_status);
            $order_info['add_date'] = local_date('Y-m-d H:i:s', $oarr['add_time']);
            $order_info['goods_num'] += $oarr['goods_number'];
            //-/　商品合计
            $order_info['goods_amount'] = $oarr['goods_amount'];
            $order_info['consignee'] = $oarr['consignee'];
            $order_info['mobile'] = $oarr['mobile'];
            $order_info['address'] = $oarr['address'];
            $order_info['address_name'] = $oarr['address_name'];
            $order_info['courier_name'] = $oarr['courier_name'];
            $order_info['courier_phone'] = $oarr['courier_phone'];
            //-/ 期望时间
            $se_date_start = local_date('Y-m-d H:i:s', $oarr['shipping_expect_time_start']);
            $order_info['shipping_expect_start'] = $se_date_start;
            $se_date_end = local_date('Y-m-d H:i:s', $oarr['shipping_expect_time_end']);
            $order_info['shipping_expect_end'] = $se_date_end;
            $order_info['shipping_expect'] = "{$se_date_start} 到 {$se_date_end}";
            $order_info['postscript'] = $oarr['postscript'];
            $order_info['pay_id'] = $oarr['pay_id'];
            $order_info['pay_type'] = $p_server->get_pay_type($oarr['pay_id']);
            $order_info['shipping_fee'] = $oarr['shipping_fee'];
            //-/ 实付金额
            $order_info['pay_fee'] = $oarr['pay_fee'];
        
            $goods_tmp['goods_id'] = $oarr['goods_id'];
            $goods_tmp['goods_name'] = $oarr['goods_name'];
            $goods_tmp['sku_id'] = $oarr['sku_id'];
            $goods_tmp['goods_price'] = $oarr['goods_price'];
            $goods_tmp['market_price'] = $oarr['market_price'];
            $goods_tmp['goods_number'] = $oarr['goods_number'];
            $goods_tmp['main_attr_name'] = $oarr['main_attr_name'];
            $goods_tmp['main_attr_value_name'] = $oarr['main_attr_value_name'];
            $goods_tmp['sec_attr_name'] = $oarr['sec_attr_name'];
            $goods_tmp['sec_attr_value_name'] = $oarr['sec_attr_value_name'];
            $goods_tmp['goods_img'] = $oarr['goods_img'];
            $order_goods[] = $goods_tmp;
        }
        $data['order_info'] = $order_info;
        $data['order_goods'] = $order_goods;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 购物车结算列表
     * 
     * @param int uid 用户ID;
     * @param int store_id 店铺ID;
     * 
     * @author ^2_3^
     */
    public function cart_settle_account() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        if( empty($uid) || empty($store_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array(
            'store_id' => $store_id
        );
        $store_info = M('wm_store s')
            ->field('
                	s.store_id,
                	s.seller_id,
                	s.store_name,
                	s.store_img,
                	s.shipping_fee,
                	s.starting_money,
                    s.scc_id
                ')
            ->where($where_s)
            ->find();
        if( empty($store_info) ) {
            returnApiError('提示:店铺参数错误;');
            
        }else if( empty($store_info['scc_id']) ) {
            returnApiError('提示:店铺物流点没设置;');
        }
        $data['store_info'] = $store_info;
        
        /// 用户默认地址
//         $where_ua = array(
//             "user_id" => $uid,
//             "default" => 1
//         );
//         $ua_fields = "
//             ua.address_id,
//         	ua.user_id,
//         	ua.consignee,
//         	ua.mobile,
//         	ua.address,
//         	ua.address_name,
//         	ua.sign_building,
//         	ua.longitude,
//         	ua.latitude,
//             ua.address_tag
//         ";
//         $ua_info = M('user_address ua')
//             ->field( $ua_fields )
//             ->where($where_ua)
//             ->find();
// // $arr_error['user_da_sql'] = M()->getLastSql();
        //-/ 用户地址
//         if( empty($ua_info) ) {
//             unset( $where_ua['default'] );
//             $ua_info = M('user_address ua')
//                 ->field( $ua_fields )
//                 ->where($where_ua)
//                 ->find();
// // $arr_error['user_fa_sql'] = M()->getLastSql();
//         }
//         $data['user_address'] = $ua_info;
        
        /// 用户匹配地址
        $has_address = 0;
        $info_u_address = array();
        $list_time = array();
        $where_ua = array(
            "ua.user_id" => $uid
        );
        $field_u_address = '
            ua.address_id,
        	ua.user_id,
        	ua.consignee,
        	ua.mobile,
        	ua.address,
        	ua.address_name,
        	ua.sign_building,
        	ua.longitude,
        	ua.latitude,
        	ua.address_tag,
        	ua.`default`
        ';
        $list_u_address = M('user_address ua')
            ->field($field_u_address)
            ->where($where_ua)
            ->order('ua.`default` DESC')
            ->select();
// w_log('cyb_log', '用户匹配地址 '.M()->getLastSql());
        //-/ 判断地址是否超区
        $bscservice = new BscService();
        foreach ( $list_u_address as $u_key=>$u_arr ){
            // 配送时段
            $result_time = $bscservice->get_order_freight_time(
                $u_arr['longitude'], $u_arr['latitude'], $store_info['scc_id']
            );
            
            if( $result_time['status'] ) {
                $info_u_address = $u_arr;
                $has_address = 1;
                $list_time = $result_time['distribution_time']['list'];
                break;
            }
        }
        $data['user_address'] = $info_u_address;
        $data['has_address'] = $has_address;
        $data['list_time'] = $list_time;
        
        /// 配送时段
//         if( !empty($ua_info) ) {
//             $bscservice = new BscService();
//             $result_time = $bscservice->get_order_freight_time(
//                 $ua_info['longitude'], $ua_info['latitude'], $store_info['scc_id']
//             );
            
            /// 调试
//             $arr_error['longitude'] = $ua_info['longitude'];
//             $arr_error['latitude'] = $ua_info['latitude'];
//             $arr_error['scc_id'] = $store_info['scc_id'];
//             $arr_error['result_time'] = $result_time;
//             returnApiSuccess($arr_error);
            
//             if( !$result_time['status'] ) {
//                 returnApiError('提示:超区,请重新定位;', $result_time);
//             }
//             $data['list_time'] = $result_time['distribution_time']['list'];
//         }
        
        /// 商品列表
        $where_c = array(
            "c.uid" => $uid,
            "c.store_id" => $store_id
        );
        $goods_list = M('wm_cart c')
            ->field('
            	c.cart_id,
            	c.uid,
            	c.store_id,
            	
            	c.goods_id,
            	c.goods_name,
            	c.sku_id,
            	c.market_price AS c_market_price,
            	c.goods_price AS c_goods_price,
            	c.goods_num,
            
            	g.market_price AS g_now_market_price,
            	g.goods_price AS g_now_goods_price,
            	g.is_sku,
            	g.state,
            	g.is_del AS g_is_del,
            
                gs.main_attr_id,
            	gs.main_attr_name,
            	gs.main_attr_value_id,
            	gs.main_attr_value_name,
            	gs.sec_attr_id,
            	gs.sec_attr_name,
            	gs.sec_attr_value_id,
            	gs.sec_attr_value_name,
            	gs.goods_money AS gs_now_goods_price,
            	gs.is_del AS gs_is_del
            ')
            ->join('sdx_wm_goods g ON g.goods_id = c.goods_id', 'left')
            ->join('sdx_wm_goods_sku gs ON gs.sku_id = c.sku_id', 'left')
            ->where($where_c)
            ->select();
// w_log('cyb_log', M()->getLastSql());
        
        /// 商品统计
        //-/ 商品数量
        $goods_count = 0;
        //-/ 商品总额
        $goods_amount = 0;
        //-/ 下架/删除商品
        $arr_g_off = array();   //下架商品列表;
        $arr_c_off = array();   //下架商品购物车ID列表;
        $str_off_gname = '';    //下架商品删除提示信息;
        $has_off = 0;           //是否包含下架商品;
        foreach ( $goods_list as $g_key=>$g_arr ){
            //-/ 下架/删除商品
            if( $g_arr['state'] != 1 || $g_arr['is_del'] == 1 
                || ( $g_arr['is_sku'] && $g_arr['sku_id'] && $g_arr['gs_is_del'] == 1 ) ) {
                
                $arr_g_off[] = $g_arr;
                $arr_c_off[] = $g_arr['cart_id'];
                $str_off_gname .= "{$g_arr['goods_name']}, ";
                unset( $goods_list[ $g_key ] );
                continue;
            }
            
            //-/ 商品最新价格
            $goods_price = 0;
            if( $g_arr['is_sku'] || $g_arr['sku_id'] ){
                $goods_price = $g_arr['gs_now_goods_price'];
                
            }else {
                $goods_price = $g_arr['g_now_goods_price'];
            }
            $goods_list[$g_key]['goods_price'] = $goods_price;
            
            //-/ 商品数量
            $goods_count += $g_arr['goods_num'];
            //-/ 商品总额
            $goods_amount += $goods_price * $g_arr['goods_num'];
        }
        
        if( !empty($arr_g_off) ) {
            $has_off = 1;
            $str_off_gname = trim( $str_off_gname, ', ' );
            $str_off_gname = "所选的“{$str_off_gname}”已经下架，请选择其他;";
            
            /// 清除购物车下架商品
            $str_off_cid = implode( $arr_c_off, ',');
            $where_c_d['cart_id'] = array( 'IN', $str_off_cid );
            $flag_c_d = M('wm_cart')->where( $where_c_d )->delete();
// w_log( 'cyb_log', '购物车结算列表_删除购物车下架商品: '.M()->getLastSql() );

            $arr_err['goods_off'] = $arr_g_off;
            returnApiError($str_off_gname, $arr_err);
        }
        
//         $data['goods_off_list'] = $arr_g_off;
//         $data['has_off'] = $has_off;
//         $data['off_tip_msg'] = $str_off_gname;
        $data['godds_list'] = $goods_list;
        $data['goods_count'] = $goods_count;
        $data['goods_amount'] = $goods_amount;
        $data['pay_fee'] = $goods_amount + $store_info['shipping_fee'];
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 用户地址(标识是否匹配当前商家配送范围)
     * 
     * @param int $uid 用户ID;
     * @param int $store_id 店铺ID;
     * 
     * @author ^2_3^
     */
    public function get_u_address_list() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        if( empty($uid) || empty($store_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array(
            'store_id' => $store_id
        );
        $store_info = M('wm_store s')
            ->field('
            	s.store_id,
            	s.seller_id,
            	s.store_name,
            	s.store_img,
            	s.shipping_fee,
            	s.starting_money,
                s.scc_id
            ')
            ->where($where_s)
            ->find();
        if( empty($store_info) ) {
            returnApiError('提示:店铺参数错误;');
        
        }else if( empty($store_info['scc_id']) ) {
            returnApiError('提示:店铺物流点没设置;');
        }
        $data['store_info'] = $store_info;
        
        /// 用户地址列表
        $where_ua = array(
            "ua.user_id" => $uid
        );
        $field_u_address = '
            ua.address_id,
        	ua.user_id,
            ua.country,
            ua.province,
            ua.city,
            ua.district,
            ua.zipcode,
        	ua.consignee,
        	ua.mobile,
        	ua.address,
        	ua.address_name,
        	ua.sign_building,
        	ua.longitude,
        	ua.latitude,
        	ua.address_tag,
            ua.sex,
        	ua.`default` AS is_default
        ';
        $list_u_address = M('user_address ua')
            ->field($field_u_address)
            ->where($where_ua)
            ->order('ua.`default` DESC')
            ->select();
        //-/ 判断地址是否超区
        $bscservice = new BscService();
        foreach ( $list_u_address as $u_key=>$u_arr ){
            $is_match = 0; //是否匹配;
            
            $country_name = M('region')
                ->where('region_id ='.$u_arr['country'])
                ->getField('region_name');
            $list_u_address[ $u_key ]['country_name'] = $country_name;
            
            $province_name = M('region')
                ->where('region_id ='.$u_arr['province'])
                ->getField('region_name');
            $list_u_address[ $u_key ]['province_name'] = $province_name;
            
            $city_name = M('region')
                ->where('region_id ='.$u_arr['city'])
                ->getField('region_name');
            $list_u_address[ $u_key ]['city_name'] = $city_name;
            
            $district_name = M('region')
                ->where('region_id ='.$u_arr['district'])
                ->getField('region_name');
            $list_u_address[ $u_key ]['district_name'] = $district_name;
            
            // 配送时段
            if( $u_arr['longitude'] < $u_arr['latitude'] ) {
                //-/ 地址异常:反转经纬度;
                $list_u_address[ $u_key ]['longitude'] = $u_arr['latitude'];
                $list_u_address[ $u_key ]['latitude'] = $u_arr['longitude'];
            }
            $result_time = $bscservice->get_order_freight_time(
                $list_u_address[ $u_key ]['longitude'], $list_u_address[ $u_key ]['latitude'], $store_info['scc_id']
            );
        
            if( $result_time['status'] ) {
                $is_match = 1;
            }
            $list_u_address[$u_key]['is_match'] = $is_match;
        }
        $data['list'] = $list_u_address;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess( $data );
    }
    
    /**
     * 用户地址检查(是否匹配商家配送区)
     * 
     * @param int store_id 店铺id;
     * @param int user_id 用户ID;
     * @param string open_id 微信用户唯一识别;
     * @param string province 省份;
     * @param string city 城市;
     * @param string district 市区;
     * @param string address 详细地址; 
     * @param string sign_building 地标;
     * 
     * @author ^2_3^
     */
    public function user_address_check() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数获取
        $store_id = I('post.store_id', 0, 'int');
        $user_id = I('post.user_id', 0, 'int');
        $open_id = I('post.open_id', '', 'trim');
        $province = I('post.province', '', 'trim');
        $city = I('post.city', '', 'trim');
        $district = I('post.district', '', 'trim');
        $address = I('post.address', '', 'trim');
        $sign_building = I('post.sign_building', '', 'trim');
        
        /// 参数处理
        if( 
            empty($store_id) || empty($user_id) || empty($province) 
            || empty($city) || empty($district) || empty($address) 
        ) {
            returnApiError('提示:参数缺失;');
        }
        //-/ 详细地址
        $address = str_replace( array($province, $city, $district), 
            array('', '', ''), $address);
        if( !strstr($address, $sign_building) ) {
            $address .= $sign_building;
        }
        
        $u_address_m = new UseraddressModel();
        $province_id = $u_address_m->get_address_id($province, 1);
        $city_id = $u_address_m->get_address_id($city, 2);
        $district_id = $u_address_m->get_address_id($district, 3);
        if(!$province_id || !$city_id || !$district_id){
            returnApiError('提示:所选地址不在服务范围内，请重新选择;');
        }
        
        /// 地址经度纬度
        $address = $province.$city.$district.$address;
        $lnglat = get_lng_lat($address);
        if ($lnglat) {
            $longitude = $lnglat['lng'];
            $latitude = $lnglat['lat'];
        } else {
            returnApiError('提示:无法定位经纬度, 请重新定位;');
        }
        
        /// 店铺信息
        /// 店铺信息
        $where_s = array(
            'store_id' => $store_id
        );
        $store_info = M('wm_store s')
            ->field('
                	s.store_id,
                	s.seller_id,
                	s.store_name,
                	s.store_img,
                	s.shipping_fee,
                	s.starting_money,
                    s.scc_id
                ')
                ->where($where_s)
                ->find();
        if( empty($store_info) ) {
            returnApiError('提示:店铺参数错误;');
        
        }else if( empty($store_info['scc_id']) ) {
            returnApiError('提示:店铺物流点没设置;');
        }
        
        /// 配送时段
        $bscservice = new BscService();
        $list_time = $bscservice->get_order_freight_time(
            $longitude, $latitude, $store_info['scc_id']
        );
        
        if( !$list_time['status'] ) {
            returnApiError('提示:超出店铺配送区,请重新定位;', $list_time);
        }
        $data['list_time'] = $list_time['distribution_time']['list'];
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess( $data );
    }
    
    /**
     * 获取地址配送时段
     * 
     * @param int $uid 用户ID;
     * @param int $store_id 店铺ID;
     * @param int $address_id 用户地址ID; 
     * 
     * @author ^2_3^
     */
    public function get_delivery_time() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        $address_id = I('post.address_id', 0, 'int');
        
        if( empty($uid) || empty($store_id) || empty($address_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 用户地址
        $where_ua = array(
            'ua.user_id' => $uid,
            'ua.address_id' => $address_id
        );
        $u_address_info = M("user_address ua")
            ->field("
                ua.address_id,
            	ua.user_id,
            	ua.consignee,
            	ua.`default`,
            	ua.longitude,
            	ua.latitude
            ")
            ->where( $where_ua )
            ->find();
// w_log( 'cyb_log', M()->getLastSql() );
        if( empty($u_address_info) || $u_address_info['user_id'] != $uid ) {
            returnApiError('提示:用户地址参数错误;');
        }
        
        /// 店铺信息
        $where_ws = array(
            'ws.store_id' => $store_id
        );
        $store_info = M('wm_store ws')
            ->field("
                ws.store_id,
            	ws.seller_id,
            	ws.store_name,
            	ws.shipping_fee,
            	ws.starting_money,
            	ws.scc_id
            ")
            ->where( $where_ws )
            ->find();
// w_log('cyb_log', M()->getLastSql());
        if( empty($store_info) ) {
            returnApiError('提示:店铺参数错误;');
        }

        $bscservice = new BscService();
        if( $u_address_info['longitude'] < $u_address_info['latitude']) {
            $u_longitude = $u_address_info['longitude'];
            $u_address_info['longitude'] = $u_address_info['latitude'];
            $u_address_info['latitude'] = $u_longitude;
        }
        $list_time = $bscservice->get_order_freight_time(
            $u_address_info['longitude'], $u_address_info['latitude'], $store_info['scc_id']
        );
        
        /// 调试
//         $arr_error['r_address_id'] = $address_id;
//         $arr_error['address_id'] = $u_address_info['address_id'];
//         $arr_error['longitude'] = $u_address_info['longitude'];
//         $arr_error['latitude'] = $u_address_info['latitude'];
//         $arr_error['scc_id'] = $store_info['scc_id'];
//         $arr_error['list_time'] = $list_time;
//         exit( json_encode($arr_error) );
        
        if( !$list_time['status'] ) {
            $arr_error['address_id'] = $u_address_info['address_id'];
            $arr_error['longitude'] = $u_address_info['longitude'];
            $arr_error['latitude'] = $u_address_info['latitude'];
            $arr_error['scc_id'] = $store_info['scc_id'];
            $arr_error['list_time'] = $list_time;
            
            returnApiError('提示:超区,请重新定位;', $arr_error);
        }
        $data['list_time'] = $list_time['distribution_time']['list'];
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess( $data );
    }
    
    /**
     * 购物车清空
     * 
     * @param int uid 用户ID;
     * @param int store_id 店铺ID;
     * 
     * @author ^2_3^
     */
    public function cart_empty(){
        $start = microtime(true);
        
        // 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        if( empty($uid) || empty($store_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 清空购物车
        $where_c = array(
            "store_id" => $store_id,
            "uid" => $uid
        );
        $flag = M('wm_cart')
            ->where($where_c)
            ->delete();
// w_log('cyb_log', M()->getLastSql());
        
        if( $flag === false ) {
            returnApiError('提示:清空购物车失败, 请稍后重试;');
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 购物车商品列表
     * 
     * @param int uid 用户ID;
     * @param int store_id 店铺ID;
     * 
     * @author ^2_3^
     */
    public function cart_goods_list() {
        $start = microtime(true);
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        if( empty($uid) || empty($store_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息(配送费用、起送金额)
        $where_s = array(
            "store_id" => $store_id
        );
        $store_info = M('wm_store')
            ->where($where_s)
            ->find();
        if( empty($store_info) ){
            returnApiError('提示:无效参数;');
        }
        // 配送费
        $data['shipping_fee'] = $store_info['shipping_fee'];
        // 起送金额
        $data['starting_money'] = $store_info['starting_money'];
        
        /// 商品列表
        $where_c = array(
            "c.store_id" => $store_id,
            "c.uid" => $uid,
            "g.state" => 1,
            "g.is_del" => 0
        );
        $goods_list = M('wm_cart c')
            ->field('
            	c.cart_id,
            	c.uid,
            	c.store_id,
            	c.goods_id,
            	c.goods_name,
            	c.sku_id,
            	c.goods_price,
            	c.goods_num,
                g.menu_id,
            	gs.main_attr_id,
            	gs.main_attr_name,
            	gs.main_attr_value_id,
            	gs.main_attr_value_name,
            	gs.sec_attr_id,
            	gs.sec_attr_name,
            	gs.sec_attr_value_id,
            	gs.sec_attr_value_name
            ')
            ->join("sdx_wm_goods g ON g.goods_id = c.goods_id", "LEFT")
            ->join("sdx_wm_goods_sku gs ON gs.goods_id = c.goods_id AND gs.sku_id = c.sku_id AND gs.is_del = 0", "LEFT")
            ->where($where_c)
            ->select();
// w_log('cyb_log', M()->getLastSql());

        /// 购物车统计
        $goods_count = 0;
        $goods_amount = 0;
        foreach ( $goods_list as $g_key=>$g_arr ){
            $goods_count += $g_arr['goods_num'];
            $goods_amount += $g_arr['goods_price'] * $g_arr['goods_num'];
            $goods_list[$g_key]['goods_amount'] = $g_arr['goods_price'] * $g_arr['goods_num'];
            
            if( empty($g_arr['main_attr_id']) ) {
                unset( $goods_list[ $g_key ]['main_attr_id'] );
                unset( $goods_list[ $g_key ]['main_attr_name'] );
                unset( $goods_list[ $g_key ]['main_attr_value_id'] );
                unset( $goods_list[ $g_key ]['main_attr_value_name'] );
            }
            if( empty($g_arr['sec_attr_id']) ) {
                unset( $goods_list[ $g_key ]['sec_attr_id'] );
                unset( $goods_list[ $g_key ]['sec_attr_name'] );
                unset( $goods_list[ $g_key ]['sec_attr_value_id'] );
                unset( $goods_list[ $g_key ]['sec_attr_value_name'] );
            }
        }
        $data['goods_list'] = $goods_list;
        $data['goods_count'] = $goods_count;
        $data['goods_amount'] = $goods_amount;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 增减购物车
     * 
     * @param int uid 用户ID;
     * @param int store_id 店铺ID;
     * @param int goods_id 商品ID;
     * @param int main_attr_id 主要属性ID;
     * @param int main_attr_value_id 主要属性值ID;
     * @param int sec_attr_id 次要属性ID;
     * @param int sec_attr_value_id 次要属性值ID;
     * @param string source 设备来源;
     * @param string version 来源版本号(可选);
     * @param string opt_type 操作类型, add增加, decrease减少;
     * 
     * @author ^2_3^
     */
    public function cart_add_decrease() {
        $start = microtime(true);
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');
        $main_attr_id = I('post.main_attr_id', 0, 'int');
        $main_attr_value_id = I('post.main_attr_value_id', 0, 'int');
        $sec_attr_id = I('post.sec_attr_id', 0, 'int');
        $sec_attr_value_id = I('post.sec_attr_value_id', 0, 'int');
        $source = I('post.source', '', 'trim');
        $version = I('post.version', '', 'trim');
        $opt_type = I('post.opt_type', '', 'trim');
        if( empty($uid) || empty($store_id) || empty($goods_id) || empty($source) 
            || !in_array($opt_type, array('add', 'decrease')) ) {
            returnApiError('提示:参数缺失或错误;');
        }
        
        /// 商品信息
        $where_g = array(
            'g.state' => 1, //商品状态: 0未上架, 1上架, 2下架, 3平台强制下架;
            'g.is_del' => 0,
            'g.goods_id' => $goods_id,
            'g.store_id' => $store_id
        );
        $where_sku = "
            AND gs.main_attr_id = {$main_attr_id} 
            AND gs.main_attr_value_id = {$main_attr_value_id} 
            AND gs.sec_attr_id = {$sec_attr_id} 
            AND gs.sec_attr_value_id = {$sec_attr_value_id} 
            AND gs.is_del = 0
        ";
        $goods_info = M('wm_goods g')
            ->field('
                g.seller_id,
                g.store_id,
                g.goods_id,
            	g.goods_name,
                g.is_sku,
            	gs.sku_id,
            	g.market_price,
            	g.goods_price AS g_goods_price,
            	gs.goods_money AS gs_goods_price,
            	gs.main_attr_value_name,
            	gs.sec_attr_value_name
              ')
            ->join("sdx_wm_goods_sku gs ON gs.goods_id = g.goods_id {$where_sku}", "LEFT")
            ->where($where_g)
            ->find();
// w_log('cyb_log', M()->getLastSql());

        /// 验证有无商品
        if( empty($goods_info) ) {
            returnApiError('提示:没有此商品或已下架,试着刷新店铺商品列表;');
        }
        
        /// 验证属性是否正确
        if( $goods_info['is_sku'] && empty($goods_info['sku_id']) ) {
            returnApiErrorExample('提示:没有此SKU商品或已下架,试着刷新店铺商品列表;');
        }
        
        /// 增减购物车
        $data['store_id'] = $goods_info['store_id'];
        $data['goods_id'] = $goods_info['goods_id'];
        $data['sku_id'] = $goods_info['sku_id'];
        //-/ 判断是否已有
        $where_c = array(
            "uid" => $uid,
            "store_id" => $store_id,
            "goods_id" => $goods_info['goods_id']
        );
        !empty($goods_info['sku_id']) && $where_c['sku_id'] = $goods_info['sku_id'];
        $cart_find = M('wm_cart')->where($where_c)->find();
// w_log('cyb_log', M()->getLastSql());
        //-/ 添加
        if( $opt_type == 'add' && empty($cart_find) ) {
            $goods_num = 1;
            
            $cart_adata = array(
                "uid" => $uid,
                "store_id" => $goods_info['store_id'],
                "goods_id" => $goods_info['goods_id'],
                "goods_name" => $goods_info['goods_name'],
                "sku_id" => empty($goods_info['sku_id']) ? 0 : $goods_info['sku_id'],
                "market_price" => $goods_info['market_price'],
                "goods_price" => empty($goods_info['gs_goods_price']) ? $goods_info['g_goods_price'] : $goods_info['gs_goods_price'],
                "goods_num" => $goods_num,
                "source" => $source,
                "version" => $version,
                "add_time" => time()
            );
            $flag = M('wm_cart')->data($cart_adata)->add(); //add()返回新增ID;
        }
        //-/ 更新
        else if( !empty($cart_find) ) {
            // 商品数量
            $goods_num = $opt_type == 'decrease' ? $cart_find['goods_num'] - 1 : $cart_find['goods_num'] + 1;
            $cart_udata = array(
                "market_price" => $goods_info['market_price'],
                "goods_price" => empty($goods_info['gs_goods_price']) ? $goods_info['g_goods_price'] : $goods_info['gs_goods_price'],
                "goods_num" => $goods_num,
                "source" => $source,
                "version" => $version,
                "update_time" => time()
            );
            
            if( $goods_num >= 1 ) {
                $flag = M('wm_cart')->data($cart_udata)->where("cart_id = {$cart_find['cart_id']}")->save();
            }else {
                $flag = M('wm_cart')->where("cart_id = {$cart_find['cart_id']}")->delete();
                $data['opt_type'] = 'decrease';
                $data['flag'] = $flag;
            }
            
        }else {
            returnApiError('提示:购物车无效操作;');
        }
        $data['goods_num'] = $goods_num;
        
        if( !$flag ) {
            returnApiError('提示:添加购物车失败;');
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 商品规格列表
     * 
     * @param int uid 用户ID;
     * @param int seller_id 商家用户ID;
     * @param int store_id 店铺ID;
     * @param int goods_id 商品ID;
     * 
     * @author ^2_3^
     */
    public function get_goods_attr_list() {
        $start = microtime(true);
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $seller_id = I('post.seller_id', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');
        if( empty($uid) || empty($store_id) || empty($goods_id) ) {
            returnApiError('提示: 参数缺失;');
        }
        
        /// 商品SKU列表
        $where_gs = array(
            'gs.is_del' => 0
            ,'gs.goods_id' => $goods_id
        );
        $goods_sku_list = M('wm_goods_sku gs')
            ->field('
                gs.sku_id,
            	gs.sku_code,
            	gs.main_attr_id,
            	gs.main_attr_name,
            	gs.main_attr_value_id,
            	gs.main_attr_value_name,
            	gs.sec_attr_id,
            	gs.sec_attr_name,
            	gs.sec_attr_value_id,
            	gs.sec_attr_value_name,
            	gs.goods_id,
            	gs.goods_money,
            	gs.stock_num  
              ')
            ->where( $where_gs )
            ->select();
// w_log('cyb_log', M()->getLastSql());

        /// 数据处理
        //-/ 主属性(如规格)
        $main_attr = array();
        $main_attr_ids = array();
        //-/ 次属性(如口味)
        $sec_attr = array();
        $sec_attr_ids = array();
        //-/ sku商品价格列表
        $price_list = array();
        foreach ( $goods_sku_list as $gs_key=>$gs_arr ){
            //-/ 主属性数据组装
//             $main_attr[ $gs_arr['main_attr_id'] ]['main_attr_id'] = $gs_arr['main_attr_id'];
//             $main_attr[ $gs_arr['main_attr_id'] ]['main_attr_name'] = $gs_arr['main_attr_name'];
//             $main_attr[ $gs_arr['main_attr_id'] ]['value_arr'][ $gs_arr['main_attr_value_id'] ] = array(
//                 'main_attr_value_id' => $gs_arr['main_attr_value_id'],
//                 'main_attr_value_name' => $gs_arr['main_attr_value_name']
//             );
            $main_key = "{$gs_arr['main_attr_id']}_{$gs_arr['main_attr_value_id']}";
            if( $gs_arr['main_attr_id'] && !in_array($main_key, $main_attr_ids) ) {
                $main_attr[] = array(
                    'main_attr_id' => $gs_arr['main_attr_id'],
                    'main_attr_name' => $gs_arr['main_attr_name'],
                    'main_attr_value_id' => $gs_arr['main_attr_value_id'],
                    'main_attr_value_name' => $gs_arr['main_attr_value_name']
                );
                
                $main_attr_ids[] = $main_key;
            }
            
            //-/ 次属性数据组装
//             $sec_attr[ $gs_arr['sec_attr_id'] ]['sec_attr_id'] = $gs_arr['sec_attr_id'];
//             $sec_attr[ $gs_arr['sec_attr_id'] ]['sec_attr_name'] = $gs_arr['sec_attr_name'];
//             $sec_attr[ $gs_arr['sec_attr_id'] ]['value_arr'][ $gs_arr['sec_attr_value_id'] ] = array(
//                 'sec_attr_value_id' => $gs_arr['sec_attr_value_id'],
//                 'sec_attr_value_name' => $gs_arr['sec_attr_value_name']
//             );
            $sec_key = "{$gs_arr['sec_attr_id']}_{$gs_arr['sec_attr_value_id']}";
            if( $gs_arr['sec_attr_id'] && !in_array( $sec_key, $sec_attr_ids) ) {
                $sec_attr[] = array(
                    'sec_attr_id' => $gs_arr['sec_attr_id'],
                    'sec_attr_name' => $gs_arr['sec_attr_name'],
                    'sec_attr_value_id' => $gs_arr['sec_attr_value_id'],
                    'sec_attr_value_name' => $gs_arr['sec_attr_value_name']
                );
                
                $sec_attr_ids[] = $sec_key;
            }
            
            //-/ sku商品价格列表
            $price_key = "{$main_key}_{$sec_key}";
            $price_list[] = array(
                'key' => $price_key,
                'goods_money' => $gs_arr['goods_money']
            );
        }
        $data['main_attr'] = $main_attr;
        $data['sec_attr'] = $sec_attr;
        $data['price_list'] = $price_list;
        $data['goods_sku_list'] = $goods_sku_list;
        
        if( empty($data['main_attr']) ) {
            returnApiError('提示:没有设置sku商品;', $data);
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 店铺商品列表
     * 
     * @param int $uid 用户ID;
     * @param int $seller_id 商家用户ID;
     * @param int $store_id 店铺ID;
     * 
     * @author ^2_3^
     */
    public function get_store_goods_list() {
        $start = microtime(true);
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $seller_id = I('post.seller_id', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        if( empty($uid) || empty($store_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        // store_sw 店铺开关（1：营业，2：休息）（商家设置）;
        // store_audit 店铺审核状态（1：通过，2：未审核，3：不通过）;
        // is_on_line 店铺是否上线（1：上线，2：下线）（后台设置）;
        $where_s = array(
            "s.store_id" => $store_id
            ,"s.is_on_line" => 1
            ,"s.store_audit" => 1
        );
        $store_info = M('wm_store s')
            ->field('
                s.seller_id,
            	s.store_id,
            	s.store_name,
            	s.store_introduce,
            	s.store_img,
                s.shipping_fee,
            	s.starting_money,
                s.start_time,
                s.end_time,
            	s.store_sw,
            	s.store_audit,
            	s.is_on_line
            ')
        	->where($where_s)
        	->find();
// w_log('cyb_log', M()->getLastSql());
        //-/ 营业/休息 状态判断
        $time_now = date('Hi');
        if( $time_now < $store_info['start_time'] || $time_now > $store_info['end_time'] ) {
            $store_info['store_sw'] = 2;
        }
        $data['store_info'] = $store_info;
        
        /// 店铺菜单
        $where_menu = array(
            "scm.is_del" => 0
            ,"scm.is_show" => 1
            ,"scm.store_id" => $store_id
        );
        $list = M('wm_store_customize_menu scm')
            ->field('scm.menu_id, scm.menu_name')
            ->where($where_menu)
            ->order('scm.sort DESC')
            ->select();
// w_log('cyb_log', M()->getLastSql());

        /// 商品列表
        $where_g = array(
            "g.store_id" => $store_id
            ,'g.is_del' => 0
            ,'g.state' => 1
        );
        $goods_arr = M('wm_goods g')
            ->field("
                g.goods_id,
            	g.goods_name,
            	g.goods_sn,
            	g.seller_id,
            	g.store_id,
            	g.is_sku,
            	g.menu_id,
	            scm.menu_name,
            	g.market_price,
            	g.goods_price,
            	g.discount,
            	g.state,
            	g.unit_id,
            	g.unit_name,
            	g.goods_img,
            	g.describe as g_describe,
            	scm.sort AS scm_sort,
            	g.sort AS g_sort,
            	gs.sku_id,
            	gs.main_attr_id,
            	gs.main_attr_name,
            	gs.main_attr_value_id,
            	gs.main_attr_value_name,
            	gs.sec_attr_id,
            	gs.sec_attr_name,
            	gs.sec_attr_value_id,
            	gs.sec_attr_value_name,
            	gs.goods_money AS gs_goods_money
            ")
            ->join('sdx_wm_store_customize_menu scm ON scm.menu_id = g.menu_id', 'left')
            ->join('sdx_wm_goods_sku gs ON gs.goods_id = g.goods_id AND gs.is_del = 0', 'left')
            ->where($where_g)
            ->order('scm.sort DESC, g.sort DESC')
            ->select();
// w_log('cyb_log', M()->getLastSql());

        /// 商品销量
        $where_wog = array(
            'wog.store_id' => $store_id
        );
        $list_goods_sale = M("wm_order_goods wog")
            ->join("sdx_wm_order_info woi ON woi.order_id = wog.order_id")
            ->field("
                wog.goods_id,
                SUM(wog.goods_number) AS sum_goods_number
            ")
            ->where( $where_wog )
            ->group(goods_id)
            ->select();
// w_log('cyb_log', M()->getLastSql());
        $list_gsale = array();
        foreach ( $list_goods_sale as $s_key=>$s_arr ){
            $list_gsale[ $s_arr['goods_id'] ] = $s_arr['sum_goods_number'];
        }
        
        //-/ 商品列表
        $list_goods = array();
        $list_goods_ids = array();
        //-/ 主要属性
        $main_attr = array();
        $main_attr_ids = array();
        //-/ 次要属性
        $sec_attr = array();
        $sec_attr_ids = array();
        //-/ SKU价格
        $sku_price = array();
        foreach ( $goods_arr as $g_key=>$g_arr ){
            //-/ 主要属性
            $main_key = "{$g_arr['main_attr_id']}_{$g_arr['main_attr_value_id']}";
            if( $g_arr['main_attr_id'] && !in_array( $main_key, $main_attr_ids[ $g_arr['goods_id'] ]) ) {
                $main_attr[ $g_arr['goods_id'] ][] = array(
                    'main_attr_id' => $g_arr['main_attr_id'],
                    'main_attr_name' => $g_arr['main_attr_name'],
                    'main_attr_value_id' => $g_arr['main_attr_value_id'],
                    'main_attr_value_name' => $g_arr['main_attr_value_name']
                );
                unset( $g_arr['main_attr_name'] );
                unset( $g_arr['main_attr_value_name'] );
                
                $main_attr_ids[ $g_arr['goods_id'] ][] = $main_key;
            }
            
            //-/ 次要属性
            $sec_key = "{$g_arr['sec_attr_id']}_{$g_arr['sec_attr_value_id']}";
            if( $g_arr['sec_attr_id'] && !in_array($sec_key, $sec_attr_ids[ $g_arr['goods_id'] ] ) ) {
                $sec_attr[ $g_arr['goods_id'] ][] = array(
                    'sec_attr_id' => $g_arr['sec_attr_id'],
                    'sec_attr_name' => $g_arr['sec_attr_name'],
                    'sec_attr_value_id' => $g_arr['sec_attr_value_id'],
                    'sec_attr_value_name' => $g_arr['sec_attr_value_name']
                );
                unset( $g_arr['sec_attr_name'] );
                unset( $g_arr['sec_attr_value_name'] );
                
                $sec_attr_ids[ $g_arr['goods_id'] ][] = $sec_key;
            }
            
            //-/ SKU价格
            if( $g_arr['main_attr_id'] || $g_arr['sec_attr_id'] ) {
                $main_key = "{$g_arr['main_attr_id']}_{$g_arr['main_attr_value_id']}";
                $sec_key = "{$g_arr['sec_attr_id']}_{$g_arr['sec_attr_value_id']}";
                if( $g_arr['main_attr_id'] && $g_arr['sec_attr_id'] ) {
                    $price_key = "{$main_key}_{$sec_key}";
                    
                }else if($g_arr['main_attr_id'] && !$g_arr['sec_attr_id']) {
                    $price_key = "{$main_key}";
                    
                }else if(!$g_arr['main_attr_id'] && $g_arr['sec_attr_id']) {
                    $price_key = "{$sec_key}";
                }
                
                $sku_price[ $g_arr['goods_id'] ][] = array(
                    'key' => $price_key,
                    'price' => $g_arr['gs_goods_money']
                );
                unset( $g_arr['main_attr_id'] );
                unset( $g_arr['main_attr_value_id'] );
                unset( $g_arr['sec_attr_id'] );
                unset( $g_arr['sec_attr_value_id'] );
                unset( $g_arr['sku_id'] );
                unset( $g_arr['gs_goods_money'] );
            }
            
            //-/ 商品列表
            if( !in_array($g_arr['goods_id'], $list_goods_ids[ $g_arr['menu_id'] ]) ) {
                $list_goods_ids[ $g_arr['menu_id'] ][] = $g_arr['goods_id'];
                
                // 商品销量
                $g_arr['sum_goods_snumber'] = empty($list_gsale['goods_id']) ? 0 : $list_gsale['goods_id'];
                
                $list_goods[ $g_arr['menu_id' ] ][] = $g_arr;
            }
            
        }
        
        foreach ( $list as $l_key=>$l_arr ) {
            if( $list_goods[ $l_arr['menu_id'] ] ) {
                /// 商品处理
                foreach ( $list_goods[ $l_arr['menu_id'] ] as $lg_key=>$lg_arr ){
                    //-/ 主要属性
                    if( $main_attr[ $lg_arr['goods_id'] ] ) {
                        $list_goods[ $l_arr['menu_id'] ][ $lg_key ]['main_attr_list'] = $main_attr[ $lg_arr['goods_id'] ];
                    }
                    //-/ 次要属性
                    if( $sec_attr[ $lg_arr['goods_id'] ] ) {
                        $list_goods[ $l_arr['menu_id'] ][ $lg_key ]['sec_attr_list'] = $sec_attr[ $lg_arr['goods_id'] ];
                    }
                    //-/ SKU价格
                    if( $sku_price[ $lg_arr['goods_id'] ] ) {
                        $list_goods[ $l_arr['menu_id'] ][ $lg_key ]['sku_price_list'] = $sku_price[ $lg_arr['goods_id'] ];
                    }
                }
                
                $list[ $l_key ]['goods_list'] = $list_goods[ $l_arr['menu_id'] ];
            }
            
        }
        
        $data['list'] = $list;
        
        if( empty($data) ) {
            returnApiError('提示:没有相关信息;');
        }
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 店铺列表
     * 
     * @param int $uid 用户ID;
     * @param int $address_id 用户地址;
     * @param string $longitude 用户经度;
     * @param string $latitude 用户维度;
     * @param int $page 页数, 可选, 默认值为1, 表示第一页;
     * 
     * @author ^2_3^
     */
    public function get_store_list(){
        $start = microtime(true);
        
        /// 参数处理
        $uid = I('post.uid', 0, 'int');
        $address_id = I('post.address_id', 0, 'int');
        $longitude = I('post.longitude', '', 'trim');
        $latitude = I('post.latitude', '', 'trim');
        if( empty($uid) ) {
            returnApiError('提示:参数缺失;');
        }
        //-/ 页数
        $page = I('post.page', 1, 'int');
        empty($page) && $page = 1;
        
        // 结果数据
        $data = array();
        
        /// 用户定位地址
        if( !empty($address_id) ) {
            $where_u = array(
                "ua.default" => 1,
                "ua.address_id" => $address_id
            );
            $u_d_address = M('user_address ua')
                ->field("ua.sign_building, ua.address, ua.default, ua.longitude, ua.latitude")
                ->where($where_u)
                ->find();
            if( empty($u_d_address) || empty($u_d_address['longitude']) || empty($u_d_address['latitude']) ) {
                unset($u_d_address);
            }else {
                // 详细地址/地标
                $data['u_address']['all_address'] = $u_d_address['sign_building'];
                // 简要地址
                $data['u_address']['lit_address'] = $u_d_address['address'];
                $longitude = $u_d_address['longitude'];
                $latitude = $u_d_address['latitude'];
            }
            
        }
        if( empty($u_d_address) && !empty($longitude) && !empty($latitude) ) {
            $u_address = gps_to_address($longitude, $latitude);
            $data['u_address'] = $u_address;
        }
        
        if( empty($u_address['all_address']) ) {
            //-/ 用户默认地址
            $where_u = array(
                "ua.default" => 1,
                "ua.user_id" => $uid
            );
            $u_d_address = M('user_address ua')
                ->field("ua.sign_building, ua.address, ua.default, ua.longitude, ua.latitude")
                ->where($where_u)
                ->find();
// w_log('wm_log', 'get_store_list() 用户默认地址 '.M()->getLastSql());
            
            if( empty($u_d_address['longitude']) || empty($u_d_address['latitude']) ) {
                $where_u = array(
                    "ua.user_id" => $uid
                );
                $u_a_list = M('user_address ua')
                    ->field("ua.sign_building, ua.address, ua.default, ua.longitude, ua.latitude")
                    ->where($where_u)
                    ->select();
// w_log('wm_log', 'get_store_list() 用户地址列表 '.M()->getLastSql());
                foreach ( $u_a_list as $u_key=>$u_arr ){
                    if( !empty($u_arr['longitude']) && !empty($u_arr['latitude']) ) {
                        $u_d_address = $u_arr;
                        break;
                    }
                }
            }
            
            if( !empty($u_d_address) ) {
                // 详细地址/地标
                $data['u_address']['all_address'] = $u_d_address['sign_building'];
                // 简要地址
                $data['u_address']['lit_address'] = $u_d_address['address'];
                $longitude = $u_d_address['longitude'];
                $latitude = $u_d_address['latitude'];
            }
        }
        
        if( empty($longitude) || empty($latitude) ){
            //returnApiError('提示:用户没有添加地址;');
            
            /// 默认: 天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心;
            $longitude = '113.34569';
            $latitude = '23.131468';
            $data['u_address'] = array();
        }
        
        /// 店铺运营分类
        $class_list = M('wm_store_classify sc')
            ->field('sc.classify_id, sc.classify_name')
            ->where('sc.is_show = 1 AND sc.is_del = 0 AND sc.parent_id = 0')
            ->select();
        $data['class_list'] = $class_list;
        
        /// 分页设置
        $where_s = array(
            "s.store_audit" => 1,
            "s.is_on_line" => 1
        );
        //-/ 店铺数量 count
        $store_count = M('wm_store s')->where($where_s)->count();
        $data['store_count'] = $store_count;
        //-/ 页面大小
        $data["page_size"] = $page_size = C('page_size');
        //-/ 页面总数
        $data['page_num'] = $page_num = ceil($store_count/$page_size);
        $data['is_bottom'] = 0; //是否最后一页;
        if( $page >= $page_num ) {
            $data['is_bottom'] = 1;
        }
        //-/ 页数
        $data['page'] = $page;
        
        /// 店铺列表
        $limit_start = ($page - 1) * $page_size;
        $limit = " {$limit_start}, {$page_size} ";
        $fields = "
            s.store_id,
        	s.seller_id,
        	s.store_name,
        	s.store_introduce,
        	s.store_img,
        	s.shipping_fee,
        	s.starting_money,
        	s.store_sw,
        	s.store_audit,
        	s.is_on_line,
        	s.longitude,
        	s.latitude,
        	ROUND(
        		6378.138 * 2 * ASIN(
        			SQRT(
        				POW(
        					SIN(
        						(
        							{$latitude} * PI() / 180 - s.latitude * PI() / 180
        						) / 2
        					),
        					2
        				) + COS(40.042307 * PI() / 180) * COS(latitude * PI() / 180) * POW(
        					SIN(
        						(
        							{$longitude} * PI() / 180 - longitude * PI() / 180
        						) / 2
        					),
        					2
        				)
        			)
        		) * 1000
        	) AS distance
        ";
        $store_list = M("wm_store s")
            ->field($fields)
            ->where($where_s)
            ->group('s.store_id')
            ->order("distance ASC")
            ->limit($limit)
            ->select();
// w_log( "cyb_log", M()->getLastSql() );

        /// 店铺ID
        $store_ids = array();
        foreach ( $store_list as $s_key=>$s_val ){
            array_push($store_ids, $s_val['store_id']);
        }
        $store_ids_str = implode(',', $store_ids);

        /// 店铺购物车数量
        $where_cnum = "
            c.store_id IN ({$store_ids_str})
        	AND c.uid = {$uid}
        	AND g.state = 1
        	AND g.is_del = 0
        ";
        $list_store_cnum = M('wm_cart c')
            ->join('sdx_wm_goods g ON g.goods_id = c.goods_id', 'LEFT')
            ->join('sdx_wm_goods_sku gs ON gs.goods_id = c.goods_id
                	AND gs.sku_id = c.sku_id
                	AND gs.is_del = 0', 'LEFT')
            ->field('c.store_id,
                    SUM( c.goods_num ) AS sum_c_goods_num')
            ->where($where_cnum)
            ->group('c.store_id')
            ->select();
// w_log('cyb_log', '店铺购物车商品数量 '.M()->getLastSql() );
        
        /// 店铺商品销量
        $where_woi = " woi.store_id IN ({$store_ids_str}) ";
        $list_store_gnum = M("wm_order_info woi")
            ->join("sdx_wm_order_goods wog ON wog.order_id = woi.order_id", "left")
            ->field("
                woi.store_id,
                IFNULL(SUM(wog.goods_number), 0) AS sum_goods_number
            ")
            ->where( $where_woi )
            ->group('woi.store_id')
            ->select();
// w_log( "cyb_log", M()->getLastSql() );
        
        foreach ( $store_list as $sl_key=>$sl_arr ){
            foreach ( $list_store_gnum as $g_key=>$g_arr ){
                if( $sl_arr['store_id'] == $g_arr['store_id'] ) {
                    $store_list[$sl_key]['sum_sale_num'] = $g_arr['sum_goods_number'];
                }
            }
            
            /// 店铺购物车商品数量
            foreach ( $list_store_cnum as $c_key=>$c_arr ){
                if( $sl_arr['store_id'] == $c_arr['store_id'] ) {
                    $store_list[ $sl_key ]['sum_goods_num'] = $c_arr['sum_c_goods_num'];
                }
            }
        }

        $data['store_list'] = $store_list;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }

}